package com.ggb.readingtime.config

import io.swagger.v3.oas.models.OpenAPI
import io.swagger.v3.oas.models.info.Info
import org.springdoc.core.models.GroupedOpenApi
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.reactive.config.WebFluxConfigurer
import org.springframework.web.cors.reactive.CorsConfigurationSource
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource
import org.springframework.web.cors.CorsConfiguration

@Configuration
class WebFluxConfig : WebFluxConfigurer {
    /**
     * 跨域处理
     */
    @Bean
    fun corsConfigurationSource(): CorsConfigurationSource {
        val config = CorsConfiguration()
        config.allowedOrigins = listOf("*")
        config.allowedMethods = listOf("*")
        config.allowedHeaders = listOf("*")

        val source = UrlBasedCorsConfigurationSource()
        source.registerCorsConfiguration("/**", config)
        return source
    }

    @Bean
    fun adminOpenApi(@Value("\${springdoc.version}") appVersion: String?): GroupedOpenApi {
        val paths = arrayOf("/admin/**")
        val packagedToMatch = arrayOf("com.ggb.readingtime.controller.admin")
        return GroupedOpenApi.builder().group("admin")
            .addOpenApiCustomizer { openApi: OpenAPI ->
                openApi.info(
                    Info().title("管理端API").version(appVersion)
                )
            }
            .pathsToMatch(*paths).packagesToScan(*packagedToMatch)
            .build()
    }

    @Bean
    fun userOpenApi(@Value("\${springdoc.version}") appVersion: String?): GroupedOpenApi {
        val paths = arrayOf("/user/**")
        val packagedToMatch = arrayOf("com.ggb.readingtime.controller.user")
        return GroupedOpenApi.builder().group("user")
            .addOpenApiCustomizer { openApi: OpenAPI ->
                openApi.info(
                    Info().title("Stream API").version(appVersion)
                )
            }
            .pathsToMatch(*paths).packagesToScan(*packagedToMatch)
            .build()
    }
}
